package com.demo.controller;

import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.dao.TeamDao;
import com.demo.domain.TeamProfile;
import com.demo.domain.ro.OrganizeTeamRequest;
import com.demo.service.TeamService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/team")
@CrossOrigin
public class TeamController {
    @Autowired
    TeamDao teamDao;

    @Autowired
    TeamService teamService;


    //通过队伍编号查找队伍详细信息
    @AuthorizationRequired
    @Operation(summary = "得到队伍详情信息", description = "根据队伍ID")
    @RequestMapping("/getTeamProfile")
    public Result<TeamProfile> getTeamProfileController(Long tpId, HttpServletRequest request) throws ParameterException {
        if (tpId == null) {
            throw new ParameterException("tpId为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if ( uid == null) {
            throw new ParameterException("未登录");
        }
        TeamProfile teamProfile = teamService.getTeamProfileById(tpId);
        return teamProfile != null?
                Result.success(HttpStatus.SUCCESS, "查找成功", teamProfile):
                Result.success(HttpStatus.BAD_REQUEST, "无相关信息", null);
    }

    /**创建队伍（同时完成队伍基本信息和初始成员的录入）
     *
     * @param organizeTeamRequest
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @PostMapping("/organizeTeamWithInfoAndMember")
        public Result organizeTeamWithInfoAndMember(@RequestBody OrganizeTeamRequest organizeTeamRequest, HttpServletRequest request) throws Exception {

        if (organizeTeamRequest == null || organizeTeamRequest.getTeamProfile() == null
                || organizeTeamRequest.getCompositionList() == null || organizeTeamRequest.getCompositionList().size() < 1) {
            System.out.println(organizeTeamRequest.getTeamProfile());
            System.out.println(organizeTeamRequest.getCompositionList());
            throw new ParameterException("组队信息未填写完全");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        String msg = teamService.organizeTeamInfoAndMember
                (organizeTeamRequest.getTeamProfile(), organizeTeamRequest.getCompositionList(), uid);
        return Result.success(HttpStatus.SUCCESS, msg, null);
    }
}
